package com.play.airfight.managers;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

import com.play.airfight.bullets.MyBullet;
import com.play.airfight.GlobalInfo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BulletsManager {
    // 玩家子弹管理域
    public static List<MyBullet> myBullets = new ArrayList<>(); //管理我所发射子弹对象的  管理域

    int timer = 0;

    private static BulletsManager instance;

    public static BulletsManager getInstance() {
        if (instance == null) {
            instance = new BulletsManager();
        }
        return instance;
    }


    public void drawFrame(Canvas canvas) {
        Iterator myBulletsIterator = myBullets.iterator();
        while (myBulletsIterator.hasNext()) {
            MyBullet bullet = (MyBullet) myBulletsIterator.next();
            bullet.fly();
            if (bullet.isGone) {
                // 迭代移动的同时判断是否移除
                myBulletsIterator.remove();
            } else {
                drawBullet(bullet, canvas);
            }
        }
    }

    // 绘制子弹
    private void drawBullet(MyBullet bullet, Canvas canvas) {
        Paint bp = new Paint();
        Rect rect = new Rect(
                (int) (bullet.currentX - bullet.width / 2),
                (int) (bullet.currentY - bullet.height / 2),
                (int) (bullet.currentX + bullet.width / 2),
                (int) (bullet.currentY + bullet.height / 2));
        canvas.drawRect(rect, bp);
    }

    // 执行子弹逻辑
    public void execLogic() {
        timer++;
        if (timer == GlobalInfo.player_bullet_shoot_rate_per_frame) { // 计算时间间隔
            if (myBullets.size() <= 20) {
                myBullets.add(new MyBullet());

            }
            timer = 0;
        }

    }
}
